import { Game } from "../Game";
import GameConfig from "../GameConfig";
import { SquareGroup } from "../SquareGroup";
import { GameStatus, GameViewer } from "../types";
import pageConfig from "./pageConfig";
import { SquarePageViewer } from "./SquarePageViewer";
import $ from "jquery";

export class GamePageViewer implements GameViewer {
  private msgDom = $("#msg");
  private nextDom = $("#next");
  private panelDom = $("#panel");
  private scorceDom = $("#score");

  init(game: Game): void {
    // 1. 设置区域的宽高
    this.panelDom.css({
      width: GameConfig.panelSize.width * pageConfig.SquareSize.width,
      height: GameConfig.panelSize.height * pageConfig.SquareSize.height,
    });

    this.nextDom.css({
      width: GameConfig.nextSize.width * pageConfig.SquareSize.width,
      height: GameConfig.nextSize.height * pageConfig.SquareSize.height,
    });

    // 注册键盘事件
    $(document).keydown((e) => {
      if (e.keyCode === 37) {
        game.controlLeft();
      } else if (e.keyCode === 38) {
        game.controlRotate();
      } else if (e.keyCode === 39) {
        game.controlRight();
      } else if (e.keyCode === 40) {
        game.controlDown();
      } else if (e.keyCode === 32) {
        if (game.gameStatus === GameStatus.playing) {
          game.pause();
        } else {
          game.start();
        }
      }
    });
  }

  showScore(score: number) {
    this.scorceDom.html(score.toString());
  }

  onGamePause(): void {
    this.msgDom.css({
      display: "flex",
    });
    this.msgDom.find("p").html("游戏暂停");
  }
  onGameStart(): void {
    this.msgDom.hide();
  }
  onGameOver(): void {
    this.msgDom.css({
      display: "flex",
    });
    this.msgDom.find("p").html("游戏结束");
  }

  showNext(teris: SquareGroup): void {
    teris.squares.forEach((sq) => {
      sq.viewer = new SquarePageViewer(sq, this.nextDom);
    });
  }

  swtich(teris: SquareGroup): void {
    teris.squares.forEach((sq) => {
      sq.viewer?.remove();
      sq.viewer = new SquarePageViewer(sq, this.panelDom);
    });
  }
}
